﻿#include<iostream>
#include<boost/asio.hpp>
#include<set>
const int max_length = 1024;
typedef std::shared_ptr<boost::asio::ip::tcp::socket> sockptr;
std::set<std::shared_ptr<std::thread>> threads;

void session(sockptr sock) {
	try {
		while (1) {
			char buf[max_length];
			std::memset(buf, '\0', max_length);
			boost::system::error_code err_code;
			std::size_t length = sock->read_some(boost::asio::buffer(buf, max_length),err_code);
			if (err_code == boost::asio::error::eof) {
				std::cout << "对端关闭连接" << std::endl;
				break;
			}
			else if(err_code){//为0则没有错误。
				throw boost::system::system_error(err_code);
			}
			std::cout << "客户端发送了：" << buf << std::endl;
			sock->send(boost::asio::buffer(buf,length));
		}
	}
	catch (boost::system::system_error& e) {
		std::cerr << e.code() << "错误码为：" << e.what();
}
}

void server(boost::asio::io_context& ioc, unsigned short port) {
	boost::asio::ip::tcp::acceptor acceptor(ioc,
		boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
	acceptor.listen(128);
	while (1) {
		sockptr sock(new boost::asio::ip::tcp::socket(ioc));
		acceptor.accept(*sock);
		auto t = std::make_shared<std::thread>(session, sock);
		threads.insert(t);
	}
}

int main() {
	unsigned short port = 2333;
	boost::asio::io_context ioc;
	try {
		server(ioc, 2333);
		for (auto& t : threads) {
			t->join();
		}
	}
	catch (boost::system::system_error& e) {
		std::cerr << e.code() << "错误码为：" << e.what();
	}
	return 0;
}